<script setup lang="ts">
import type { DatePickValue, LastSelectOptions } from './types.ts'
import dayjs from 'dayjs'

import { ref, watchEffect } from 'vue'
import DateSelect from './DateSelect.vue'
import LastSelect from './LastSelect.vue'

const props = defineProps<{
  active: boolean
  modelValue: DatePickValue
  dateRange: number
  lastActive?: number
  lastOptions: LastSelectOptions
}>()

const emit = defineEmits<{
  submit: [value: DatePickValue, lastValue: number | undefined]
}>()

const value = ref<DatePickValue>([...props.modelValue])
const laseValue = ref(props.lastActive)

function handleLastChange(val: number) {
  laseValue.value = val
  const now = dayjs()
  const start = now.subtract(val, 'second')
  value.value = [start.unix().toString(), now.unix().toString()]
  handleSubmit()
}

function handleSubmit() {
  emit(
    'submit',
    value.value.map((v: any) => v) as DatePickValue,
    laseValue.value,
  )
}

watchEffect(() => {
  if (props.active) {
    value.value = props.modelValue.slice() as DatePickValue
    laseValue.value = props.lastActive
  }
})
</script>

<template>
  <div class="date-pop">
    <date-select
      v-model:model-value="value"
      :date-range="dateRange"
      @submit="handleSubmit"
      @clear-last-active="laseValue = void 0"
    />
    <last-select
      :model-value="laseValue"
      :options="lastOptions"
      @change="handleLastChange"
    />
  </div>
</template>
